package bill.study.designPattern.iterator.filecontent;

import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class CollectionOfCollections<E> implements Iterable<E> {
	private final Collection<Collection<E>> cOfC;

	CollectionOfCollections(Collection<Collection<E>> cOfC) {
		this.cOfC = cOfC;
	}

	private Iterator<E> currentIterator;

	@Override
	public Iterator<E> iterator() {
		return new Iterator<E>() {

			@Override
			public boolean hasNext() {
				for (Collection<E> subCollection : cOfC) {
					currentIterator = subCollection.iterator();
					if (subCollection.iterator().hasNext())
						return true;
				}
				return false;
			}

			@Override
			public E next() {
				if (currentIterator == null) {
					throw new NoSuchElementException();
				}
				return currentIterator.next();

			}

			@Override
			public void remove() {
				if (currentIterator == null) {
					throw new IllegalStateException();
				}
				currentIterator.remove();
			}
		};
	}
}
